<?php
header('Content-type: text/html; charset=UTF-8');
include 'HZip.php';
include "Classes/PHPExcel/IOFactory.php";
class user extends CI_Controller{
	
	function __construct(){
		parent::__construct();
		if (!$this->session->userdata('LoggedIn')){
			redirect('login');
		}else{
			$this->load->model('usermodel', 'user', TRUE);
			$this->load->library("pagination");
		}
	}
	
	function index(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$config = array();
        $config["base_url"] = base_url() . "user/index";
        $config["total_rows"] = $this->user->user_count();
        $config["per_page"] = 10;
        $choice = $config["total_rows"] / $config["per_page"];
    	$config["num_links"] = round($choice);
		
		$this->pagination->initialize($config);
 
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $data["results"] = $this->user->
            fetch_users($config["per_page"], $page);
        $data["links"] = $this->pagination->create_links();
 		
		$this->load->view('user', $data);
	}
	
	function create_new_user(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$data['isedit'] = false;
		
		if ($_POST){
			//load helper and library:
			$this->load->helper(array('form'));
			$this->load->library('form_validation');
					
			//set rules to validate of username, first_name, last_name, email, password, passconf:
			$this->form_validation->set_rules('text2', 'text2', 'required|min_length[3]');
			$this->form_validation->set_rules('password15', 'password15', 'required|min_length[6]|max_length[20]|matches[password16]');
			$this->form_validation->set_rules('password16', 'password16', 'required');
			$this->form_validation->set_rules('text3', 'text3', 'required|min_length[2]|max_length[20]');
			$this->form_validation->set_rules('text4', 'text4', 'required|min_length[2]|max_length[20]');
			
			if ($this->form_validation->run() == FALSE){
				
			}else{
				
				$add_info['username'] = $_POST['text2'];
				$add_info['password'] = sha1($_POST['password15']);
				$add_info['first_name'] = $_POST['text3'];
				$add_info['last_name'] = $_POST['text4'];
				$add_info['date_of_birth'] = date($_POST['date8']);
				$add_info['address'] = $_POST['text5'];
				$add_info['phone_number'] = $_POST['tel7'];
				if ($_POST['radio17'] == 'is Admin'){
					$add_info['role'] = 1;
				}elseif ($_POST['radio17'] == 'is Manager'){
					$add_info['role'] = 2;
				}else{
					$add_info['role'] = 0;
				}
				if ($_FILES["file9"]["name"]){
					if ($_FILES["file9"]["error"] > 0)
					  {
						  echo "Error: " . $_FILES["file9"]["error"] . "<br>";
					  }
					else
					  {
					  	  $url = explode("index.php", $_SERVER['PHP_SELF']);
						  $path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/user";
						  if (!file_exists($path)) {
							   mkdir($path, 0777, true);
						  }
						  
						  $tmp_name = (explode(".",$_FILES['file9']['name']));
						  $name = $add_info['username'].".".strtolower($tmp_name[1]);
						  move_uploaded_file($_FILES["file9"]["tmp_name"],
				      	  $path."/".$name);
						  $add_info['image'] = $name;
						  $this->add_zip_file($name);
					  }
				}
				
				$result = $this->user->create_new_user($add_info);
				if ($result){
					redirect('user');
				}
			}
		}
		$this->load->view('adduser', $data);
	}
	
	function edit_user(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$user_id = $_GET['id'];
		
		$user_info = $this->user->detail_user($user_id);
		
		$data['info'] = $user_info;
		
		$data['isedit'] = true;
		
		if ($_POST){
			//load helper and library:
			$this->load->helper(array('form'));
			$this->load->library('form_validation');
			
			//set rules to validate of username, first_name, last_name, email, password, passconf:
			$this->form_validation->set_rules('text2', 'text2', 'required|min_length[3]|max_length[12]');
			$this->form_validation->set_rules('password15', 'password15', 'required|min_length[6]|max_length[60]|matches[password16]');
			$this->form_validation->set_rules('password16', 'password16', 'required');
			$this->form_validation->set_rules('text3', 'text3', 'required|min_length[2]|max_length[20]');
			$this->form_validation->set_rules('text4', 'text4', 'required|min_length[2]|max_length[20]');
			
			if ($this->form_validation->run() == FALSE){
				
			}else{
				$add_info['username'] = $_POST['text2'];
				if ($user_info->password != $_POST['password15']){
					$add_info['password'] = sha1($_POST['password15']);
				}
				$add_info['first_name'] = $_POST['text3'];
				$add_info['last_name'] = $_POST['text4'];
				$add_info['date_of_birth'] = date($_POST['date8']);
				$add_info['address'] = $_POST['text5'];
				$add_info['phone_number'] = $_POST['tel7'];
				if ($_POST['radio17'] == 'is Admin'){
					$add_info['role'] = 1;
				}elseif ($_POST['radio17'] == 'is Manager'){
					$add_info['role'] = 2;
				}else{
					$add_info['role'] = 0;
				}
				
				if ($_FILES["file9"]["name"]){
					if ($_FILES["file9"]["error"] > 0)
					  {
						  echo "Error: " . $_FILES["file9"]["error"] . "<br>";
					  }
					else
					  {
					  	  $url = explode("index.php", $_SERVER['PHP_SELF']);
						  $path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/user";
						  if (!file_exists($path)) {
							   mkdir($path, 0777, true);
						  }
						  
						  $tmp_name = (explode(".",$_FILES['file9']['name']));
						  $name = $add_info['username'].".".strtolower($tmp_name[1]);
						  move_uploaded_file($_FILES["file9"]["tmp_name"],
				      	  $path."/".$name);
						  $add_info['image'] = $name;
						  $this->add_zip_file($name);
					  }
				}
				
				$result = $this->user->update_user($user_id, $add_info);
				redirect('user');
			}
		}
		$this->load->view('adduser', $data);
	}
	
	function delete_user(){
		$user_id = $_GET['id'];
		
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		$data['user_id'] = $user_id;
		
		$this->load->view('deleteuser', $data);
	}
	
	function delete(){
		$user_id = $_GET['id'];
		$this->user->delete_user($user_id);
		redirect('user');
	}
	
	function view_profile(){
		$data['id'] = $this->session->userdata('id');
		$data['name'] = $this->session->userdata('name');
		$data['image'] = $this->session->userdata('image');
		$data['date_of_birth'] = $this->session->userdata('date_of_birth');
		$data['role'] = $this->session->userdata('role');
		$data['address'] = $this->session->userdata('address');
		
		$user_id = $_GET['id'];
		
		$user_info = $this->user->detail_user($user_id);
		
		$data['info'] = $user_info;
		
		if ($_POST){
			redirect('user');
		}
		$this->load->view('profile', $data);
	}
	
	private function add_zip_file($file_name){
		$url = explode("index.php", $_SERVER['PHP_SELF']);
		$sourcePath = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/user";
		$outZipPath = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/user.zip";
		
		if (file_exists($outZipPath)){
			$zip = new ZipArchive();
			$zip->open($outZipPath);
			$zip->addFile($sourcePath."/".$file_name, "user/".$file_name);
			$zip->close();
		}else{
			HZip::zipDir($sourcePath, $outZipPath);
		}
	}
	
	public function upload_multi_user(){
		$url = explode("index.php", $_SERVER['PHP_SELF']);
		$inputFileName = $_SERVER['DOCUMENT_ROOT'].$url[0]."file_upload/user/user.xls";
		//  Read your Excel workbook
		try {
		    $inputFileType = PHPExcel_IOFactory::identify($inputFileName);
		    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
		    $objPHPExcel = $objReader->load($inputFileName);
		} catch (Exception $e) {
		    die('Error loading file "' . pathinfo($inputFileName, PATHINFO_BASENAME) . '": ' . $e->getMessage());
		}
		
		$rowIterator = $objPHPExcel->getActiveSheet()->getRowIterator();
		$array_data = array();
		foreach ($rowIterator as $row) {
		    $cellIterator = $row->getCellIterator();
		    $cellIterator->setIterateOnlyExistingCells(false);
		    $rowIndex = $row->getRowIndex();
			if ($rowIndex > 1){
				$rowIndex = $rowIndex - 2;
			    $array_data[$rowIndex] = array('username' => '', 'first_name' => '', 'last_name' => '', 'date_of_birth' => '', 'address' => '', 'phone_number' => '', 'role' => '', 'password' => '', 'passconf' => '', 'image' => '');
			
			    foreach ($cellIterator as $cell) {
			        if ('A' == $cell->getColumn()) {
			            $array_data[$rowIndex]['username'] = $cell->getCalculatedValue();
			        } else if ('B' == $cell->getColumn()) {
			            $array_data[$rowIndex]['first_name'] = $cell->getCalculatedValue();
			        } else if ('C' == $cell->getColumn()) {
			            $array_data[$rowIndex]['last_name'] = $cell->getCalculatedValue();
			        } else if ('D' == $cell->getColumn()) {
			            $array_data[$rowIndex]['date_of_birth'] = $cell->getCalculatedValue();
			        } else if ('E' == $cell->getColumn()) {
			            $array_data[$rowIndex]['address'] = $cell->getCalculatedValue();
			        } else if ('F' == $cell->getColumn()) {
			            $array_data[$rowIndex]['phone_number'] = $cell->getCalculatedValue();
			        } else if ('G' == $cell->getColumn()) {
			            $array_data[$rowIndex]['role'] = $cell->getCalculatedValue();
			        }elseif ('H' == $cell->getColumn()){
			        	$array_data[$rowIndex]['password'] = $cell->getCalculatedValue();
			        }else if ('I' == $cell->getColumn()){
			        	$array_data[$rowIndex]['passconf'] = $cell->getCalculatedValue();
			        }elseif ('J' == $cell->getColumn()){
			        	$array_data[$rowIndex]['image'] = $cell->getCalculatedValue();
			        }
			    }
			}
		}
		
		foreach ($array_data as $value) {
			if ($this->is_can_add($value)){
				$this->add_user($value);
			}
		}
		
		redirect("user");
	}
	
	private function is_can_add($user){		
		if (strlen($user['first_name']) < 2 || strlen($user['first_name']) > 20){
			return false;
		}
		
		if (strlen($user['last_name']) < 2 || strlen($user['last_name']) > 20){
			return false;
		}
		
		if (strlen($user['username']) < 3 || strlen($user['username'])> 12){
			return false;
		}
		
		if ($this->user->is_exist($user['username'])){
			return false;
		}
		
		if (strlen($user['password']) < 6 || strlen($user['password']) > 60){
			return false;
		}
		
		if ($user['password'] != $user['passconf']){
			return false;
		}
		
		if (strlen($user['phone_number']) != 0){
			if (!is_numeric($user['phone_number'])){
				return false;
			}
		}
		return true;
	}
	
	private function add_user($user){
		unset($user['passconf']);
		$user['password'] = sha1($user['password']);
		$tmp_name = $user['image'];
		if (strlen($user['image']) > 0){
			$name = (explode(".",$tmp_name));
			$name = $user['username'].".".strtolower($name[1]);
			$user['image'] = $name;
		}
		$result = $this->user->create_new_user($user);
		if ($result != false){
			if (strlen($tmp_name)){
				$url = explode("index.php", $_SERVER['PHP_SELF']);
				$inputFileName = $_SERVER['DOCUMENT_ROOT'].$url[0]."file_upload/user/image/".$tmp_name;
				echo $inputFileName;
				$path = $_SERVER['DOCUMENT_ROOT'].$url[0]."assets/img/user";
				if (file_exists($inputFileName)){
					echo "yesss";
				}
				copy($inputFileName, $path."/".$name);
				$this->add_zip_file($name);
			}
		}
	}
}